/* 
 * Copyright (c) 2010, Avdhesh yadav.
 * http://www.avdheshyadav.com
 * Contact: avdhesh.yadav@gmail.com
 *
 * This library is free software; you can redistribute it and/or modify it under the terms
 * of the GNU Lesser General Public License as published by the Free Software Foundation,
 * either version 3 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License along with this
 * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA 02111-1307, USA.
 *
 */

package com.avdy.p4j.sample.server.handler;

import java.util.ArrayList;
import java.util.List;

import net.customware.gwt.dispatch.server.ActionHandler;
import net.customware.gwt.dispatch.server.ExecutionContext;
import net.customware.gwt.dispatch.shared.ActionException;

import com.avdy.p4j.common.DAOException;
import com.avdy.p4j.sample.server.dao.LibraryDataRepository;
import com.avdy.p4j.sample.server.dao.StudentRepository;
import com.avdy.p4j.sample.shared.data.Student;
import com.avdy.p4j.sample.shared.rpc.FetchStudents;
import com.avdy.p4j.sample.shared.rpc.StudentsResult;
import com.google.inject.Inject;

public class FetchStudentsHandler implements ActionHandler<FetchStudents, StudentsResult>
{
	private final LibraryDataRepository dataRepository;

	@Inject
	public FetchStudentsHandler(final LibraryDataRepository dataRepository)
	{
		this.dataRepository = dataRepository;
	}

	@Override
	public StudentsResult execute(final FetchStudents action, final ExecutionContext context) throws ActionException 
	{
		StudentRepository studentRepository = dataRepository.getStudentRepository();
		List<Student> students = new ArrayList<Student>();	
		try 
		{
			students = (List<Student>)studentRepository.findAll(Student.class, studentRepository.initialPosition, studentRepository.ALL_ROWS);
		} catch (DAOException e) 
		{
			e.printStackTrace();
		}
		StudentsResult result = new StudentsResult(students);
		return result;
	}


	@Override
	public void rollback(final FetchStudents action,final StudentsResult result, final ExecutionContext context)throws ActionException 
	{
		// Nothing to do here
	}

	@Override
	public Class<FetchStudents> getActionType() 
	{
		return FetchStudents.class;
	}
}
